package com.amose.springcloudoauth2server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * @author yp
 * @date 2021/6/29
 * @since 1.0.0
 */
// 开启授权服务
@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    /**
     * 密码必须加密
     */
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    DataSource dataSource;

    @Bean
    TokenStore tokenStore(){
        // token 存储在数据库中
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    ApprovalStore approvalStore(){
        //给指定客户端授权通过的记录信息存储到数据库中
        return new JdbcApprovalStore(dataSource);
    }

    @Bean
    ClientDetailsService jdbcClientDetailsService(){
        // 配置了client信息查询数据库
        return new JdbcClientDetailsService(dataSource);
    }



    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 首先配置客户端授权从数据库中读取
        clients.withClientDetails(jdbcClientDetailsService());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore()) // 配置token令牌存储
                .approvalStore(approvalStore()) // 配置授权通过存储位置
                .authorizationCodeServices(authorizationCodeService());
    }

    @Bean
    AuthorizationCodeServices authorizationCodeService() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }
}
